package com.itheima.utils;

import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

public class JwtTokenUtil {

    private static final String DEFAULT_SUBJECT = "CZ_HEALTH_SUBJECT";

    private static final int default_expire_minutes = 60;

    private static String secret = "czbk_health";

    //AES加密方式
    private static SecretKey secretKey = null;

    static {
        byte[] encodedKey = new byte[0];
        try {
            encodedKey = Base64.decodeBase64(secret);
            secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String createToken(String tokenId) throws Exception {
        return createToken(tokenId,default_expire_minutes);
    }

    public static String createToken(String tokenId,int duration) throws Exception {
        //RSA加密方式
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;
        long _date = System.currentTimeMillis();
        Date now = new Date(_date);
        JwtBuilder builder = Jwts.builder()
                .setId(tokenId)
                .setIssuedAt(now)
                .setSubject(DEFAULT_SUBJECT)
                .signWith(signatureAlgorithm, RsaUtil.getPrivateKey());


        //AES加密方式
//        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//        long _date = System.currentTimeMillis();
//        Date now = new Date(_date);
//        JwtBuilder builder = Jwts.builder()
//                .setId(tokenId)
//                .setIssuedAt(now)
//                .setSubject(DEFAULT_SUBJECT)
//                .signWith(signatureAlgorithm, secretKey);

        if(duration > 0) {
            _date = _date + duration * 60 * 1000;
            builder.setExpiration(new Date(_date));
        }

        return builder.compact();
    }

    public static String parseToken(String token) throws Exception{
        Claims claims = null;
        try {
            //RSA方式
            claims = Jwts.parser()
                    .setSigningKey(RsaUtil.getPublicKey())
                    .parseClaimsJws(token).getBody();

            //AES方式
//            claims = Jwts.parser()
//                    .setSigningKey(secretKey)
//                    .parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            // TODO: handle exception
            throw new Exception("Token已过期");
        }
        return claims.getId();
    }

}
